import Vue from "vue";
import VueRouter from "vue-router";
import utils from "@/config/utils";

Vue.use(VueRouter);

const routes = [{
		path: "/",
		name: "home",
		component: () => import('../views/Home'),
		meta: {
			requireAuth: true
		}
	},
	{
		path: "/page",
		component: () => import('../views/Pages'),
		children: [{
				path: "/tags",
				name: "tags",
				component: () => import('../views/Tag/Tag'),
				meta: {
					requireAuth: true
				}
			},
			{
				path: "/fileup",
				name: "fileup",
				component: () => import('../views/FileUp/FileUp'),
				meta: {
					requireAuth: true
				}
			}
		]
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('../views/Login')
	},
	{
		path: '/register',
		name: 'register',
		component: () => import('../views/Register')
	},
	{
		path: '/test',
		name: 'test',
		component: () => import('../views/test')
	},
	{
		path: '/canvas',
		name: 'canvsTest',
		component: () => import('../views/CanvasNote')
	},
];

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
});

router.beforeEach((to, from, next) => {
	// window_app = null
	// 修改标题
	if (to.meta.title) {
		document.title = to.meta.title
	} else {
		document.title = '记事本'
	}
	if (to.matched.some(res => res.meta.requireAuth)) { // 判断是否需要登录权限
		// console.log(from);
		if (utils.getUserId()) { // 判断是否登录
			next();
		} else { // 没登录则跳转到登录界面
			if (to.path === "/login") {
				next()
			} else {
				next({
					path: "/login",
					query: {
						redirect: to.fullPath
					} //将目的路由地址存入login的query中
				})
			}
		}
	} else {
		next();
	}
})
export default router;
